<template>
  <div class="modifyPWD">
    <el-card>
      <div class="header" slot="header">修改密码</div>
      <el-form
        label-width="80px"
        :model="employee"
        :rules="rules"
        ref="empForm"
      >
        <el-form-item label="旧密码" prop="oldPassword">
          <el-input
            type="password"
            placeholder="旧密码"
            v-model="employee.oldPassword"
          ></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            type="password"
            placeholder="新密码"
            v-model="employee.newPassword"
          ></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            @keyup.enter.native="submitPassword"
            type="password"
            placeholder="确认密码"
            v-model="employee.confirmPassword"
          ></el-input>
        </el-form-item>
        <el-button type="primary" @click="submitPassword">提交</el-button>
        <el-button @click="resetData">重置</el-button>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { updatePassword } from "@/api/user";
export default {
  data() {
    return {
      employee: {
        account: "",
        oldPassword: "",
        newPassword: "",
        confirmPassword: "",
      },
      rules: {
        oldPassword: [
          { required: true, message: "请输入旧密码", trigger: "blur" },
        ],
        newPassword: [
          { required: true, message: "请输入新密码", trigger: "blur" },
        ],
        confirmPassword: [
          { required: true, message: "请输入确认密码", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    resetData() {
      this.$refs.empForm.resetFields();
    },
    submitPassword() {
      this.$refs.empForm.validate((data) => {
        // 新密码与旧密码相同
        if (data && this.employee.newPassword == this.employee.oldPassword) {
          this.$message({
            message: "新密码不能与旧密码相同",
            type: "error",
          });
          return;
        }
        // 新密码与确认密码不相同
        if (
          data &&
          this.employee.newPassword !== this.employee.confirmPassword
        ) {
          this.$message({
            message: "新密码与确认密码不相同",
            type: "error",
          });
          return;
        }
        // 需要将用户的账号一起提交
        this.employee.account = JSON.parse(localStorage.getItem("account"));
        this.employee.password = this.employee.newPassword;
        // 提交数据
        updatePassword(this.employee).then((resp) => {
          let respData = resp.data;
          if (respData.code === 20000) {
            // 密码修改成功
            this.$router.push("/");
          }
        });
      });
    },
  },
};
</script>

<style lang="less" scoped>
.modifyPWD {
  width: 100%;
  height: 100%;
  .el-form {
    width: 450px;
  }
}
</style>
